package cn.aran.sys.service.impl;

import cn.aran.basic.service.impl.BaseServiceImpl;
import cn.aran.sys.domain.Menu;
import cn.aran.sys.mapper.MenuMapper;
import cn.aran.sys.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aran
 * @since 2022-07-11
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    /**
    * @Title: save
    * @Description: 添加菜单
    * @Author: Aran
    * @Version: 1.0
    * @Date:  2022/7/11 18:46
    * @Parameters: [menu]
    * @Return void
    */
    @Override
    public void save(Menu menu) {
        menuMapper.save(menu);
        // // this.update(menu);
        // String component = "";
        // if (menu.getParent().getId() == null){
        //     component = "/" + menu.getId();
        // }else {
        //     Menu parent = menuMapper.loadById(menu.getParent().getId());
        //     if(parent != null){
        //         component = parent.getComponent() + "/" + menu.getId();
        //     }
        // }
        // menu.setComponent(component);
        // menuMapper.update(menu);
    }

    /**
    * @Title: update
    * @Description: 
    * @Author: Aran
    * @Version: 1.0
    * @Date:  2022/7/11 18:42
    * @Parameters: [menu]
    * @Return void
    */
    @Transactional
    @Override
    public void update(Menu menu) {
        // String component = "";
        // if (menu.getParent().getId() == null){
        //     component = "/" + menu.getId();
        // }else {
        //     Menu parent = menuMapper.loadById(menu.getParent().getId());
        //     if(parent != null){
        //         component = parent.getComponent() + "/" + menu.getId();
        //     }
        // }
        // menu.setComponent(component);
        menuMapper.update(menu);
    }

    /**
    * @Title: loadMenuTree
    * @Description: 菜单无限极树
    * @Author: Aran
    * @Version: 1.0
    * @Date:  2022/7/11 17:56
    * @Parameters: []
    * @Return java.util.List<cn.aran.sys.domain.Menu>
    */
    @Override
    public List<Menu> loadMenuTree() {
        // 查询所有部门数据
        List<Menu> allMenu = menuMapper.loadAll();
        Map<Long, Menu> allMap = allMenu.stream().collect(Collectors.toMap(Menu::getId, item -> item));
        List<Menu> menus = new ArrayList<>();
        for (Menu menuEmp : allMenu) {
            if (menuEmp.getParentId() == null) {
                menus.add(menuEmp);
            } else {
                Menu menu = allMap.get(menuEmp.getParentId());
                if (menu != null) {
                    menu.getChildren().add(menuEmp);
                }
            }
        }

        return menus;
    }
}
